#include "Player.h"
#include "Level.h"

Player::Player()
{
	Create("../../resource/star_ship.bmp",CVector(50,50));
    StartPosition();

    livesSprite = CCore::getInstance()->GetCurrentScene<Level>()->layerScreen->CreateSprite("../../resource/star_ship_life.bmp",CVector(39,12));
    livesSprite->Position = CVector(0.0f,(int)480-livesSprite->GetSize().fy);
    livesSprite->AddAnimation(0,true,1,3);
    livesSprite->AddAnimation(0,true,1,2);
    livesSprite->AddAnimation(0,true,1,1);
    livesSprite->AddAnimation(0,true,1,0);
    shotTimeLimt.Init(1500);
    shotTimeLimt.Restart();
}

Player::~Player()
{
}

void Player::StartPosition()
{
    Position = CVector(((int)CVideoManager::getInstance()->WindowSize.fx/2)-((int)pr_Image->FrameSize.fx/2),
                        (int)CVideoManager::getInstance()->WindowSize.fy - (int)pr_Image->FrameSize.fy);
    bVisible = true;
}

void Player::HandleLimit()
{
    if(Position.fx >= (CVideoManager::getInstance()->WindowSize.fx - pr_Image->FrameSize.fx)){
        Position.fx = CVideoManager::getInstance()->WindowSize.fx - pr_Image->FrameSize.fx;
    }

    if(Position.fx <= 0){
        Position.fx = 0;
    }
}

void Player::Execute()
{
    HandleDeath();
    HandleControls();
    HandleLimit();
    HandleShot();
    HandleLife();
    std::cout << "life points: " << lifePoints << std::endl;
    std::cout << "lives: " << playerLives << std::endl;
}

void Player::HandleLife()
{
    if(lifePoints <= 0){
        bVisible = false;
        lifePoints=1;
    }
}

void Player::HandleDeath()
{
    if(!bVisible){
        playerLives--;
        livesSprite->SetCurrentAnimation(playerLives);
        StartPosition();
    }

    if(playerLives < 0){
        exit(0);
    }
}

void Player::HandleControls()
{
    if(CInputManager::getInstance()->KeyState(SDLK_LEFT)){
        Move(-5,0);
    }

    if(CInputManager::getInstance()->KeyState(SDLK_RIGHT)){
        Move(5,0);
    }
}

void Player::Shoting()
{
    Shot* shot = new Shot(this,1);
    shot->Position = CVector(Position.fx+(pr_Image->FrameSize.fx/2.8f),Position.fy-(pr_Image->FrameSize.fy/2.8f));
    CCore::getInstance()->GetCurrentScene<Level>()->layerScreen->AddSprite(shot);
    shotTimeLimt.Restart();
}

void Player::HandleShot()
{

    if(CInputManager::getInstance()->KeyState(SDLK_SPACE)){
        if(shotTimeLimt.Ended()){
            Shoting();
        }
    }
    shotTimeLimt.Update();
}

